<?php
namespace app\common\service;

use app\common\util\Util;
use think\Model;

class FriendApplyService extends BaseService
{


    /**
     * 微信端：获取我的好友申请列表
     * @param $sid
     * @param $uid
     * @param $p
     * @param $pageSize
     * @param $only_unchecked
     */
    public function getApplyList($sid, $uid, $p, $pageSize){
        $field = 'fa.id as apply_id,fa.check_status,fa.apply_desc,s.id as apply_studentsid,s.uid as apply_uid,s.name,s.company,u.user_nickname,u.user_headimgurl';
        $order = 'fa.check_status ASC,fa.apply_time DESC,fa.check_time DESC';
        $where = [
            'fa.sid' => $sid,
            'fa.friend_uid' => $uid,
            'fa.check_status' => ['<>',2],
            's.status' => 1
        ];

        $list = db('friend_apply fa')
            ->field($field)
            ->join('students s', 'fa.my_studentsid=s.id')
            ->join('user u', 's.uid=u.user_id')
            ->where($where)
            ->order($order)
            ->limit(($p-1) * $pageSize, $pageSize)
            ->select();
        if($list){
            foreach($list as $k => $v){
                $list[$k]['company'] = Util::unserializeStr($v['company']);
            }
        }

        return $list;
    }


    /**
     * 微信端: 申请好友
     * @param $sid
     * @param $my_uid 自身用户ID
     * @param $friend_studentsid 好友学员ID
     * @param $apply_desc 申请描述（不超过20个字符）
     * @return array
     */
    public function doApply($sid, $my_uid, $friend_studentsid, $apply_desc){
        //获取自身学员ID
        $my_studensid = db('students')->where(['uid' => $my_uid, 'sid' => $sid, 'status' => 1])->value('id');
        if(!$my_studensid){
            return ['status' => 0, 'msg' => '用户信息有误'];
        }

        //查询双方是否都为学员
        $where = [
            's.id' => ['in',[$my_studensid, $friend_studentsid]],
            's.sid' => $sid,
            's.status' => 1
        ];
        $students = db('students s')
                    ->field('ui.counselor_status')
                    ->join('user_integral ui', 's.uid = ui.userid', 'LEFT')
                    ->where($where)
                    ->select();
        if(count($students) != 2){
            return ['status' => 0, 'msg' => '暂时无法申请'];
        }
        foreach ($students as $k => $v) {
            if($v['counselor_status'] == 1){
                return ['status' => 0, 'msg' => '申请失败'];
            }
        }

        //查询申请记录
        $info = db('friend_apply')
                ->where([
                    'my_studentsid' => $my_studensid,
                    'friend_studentsid' => $friend_studentsid,
                    'sid' => $sid,
                    'check_status' => ['<>', 2]
                ])
                ->find();

        if($info){
            $msg = $info['check_status'] == 0 ? '您已发出好友申请，请耐心等待对方处理' : '您们已是好友';
            return ['status' => 0, 'msg' => $msg];
        }
        $friend_uid = db('students')->where(['sid' => $sid, 'id' => $friend_studentsid])->value('uid');
        $data = [
            'my_uid' => $my_uid,
            'my_studentsid' => $my_studensid,
            'friend_uid' => $friend_uid,
            'friend_studentsid' => $friend_studentsid,
            'sid' => $sid,
            'apply_desc' => $apply_desc,
            'apply_time' => time(),
            'check_time' => time()
        ];

        $r = db('friend_apply')->insert($data);

        //发送模版消息

        return $r == false ? ['status' => 0, 'msg' => '暂时无法申请好友'] : ['status' => 1, 'msg' => '发送申请成功'];
    }


    /**
     *
     * 微信端: 好友申请审核
     * @param $sid
     * @param $uid
     * @param $apply_id 申请索引ID
     * @param $apply_uid 申请人的用户ID
     * @param $check_status 审核状态（1：同意；2：忽略）
     * @return array
     *
     */
    public function checkApply($sid, $uid, $apply_id, $apply_uid, $check_status){
        //查询是否有此申请记录
        $info = db('friend_apply')
                ->where([
                    'id' => $apply_id,
                    'sid' => $sid,
                    'my_uid' => $apply_uid,
                    'friend_uid' => $uid,
                    'check_status' => 0
                ])
                ->find();
        if(!$info){
            return ['status' => 0, 'msg' => '审核失败'];
        }

        $r = db('friend_apply')->where(['id' => $apply_id])->update(['check_status' => $check_status, 'check_time' => time()]);
        if($check_status == 1){
            //同意，则写入好友表，两条相互数据
            $data = [];
            $data[0] =  [
                'my_uid' => $uid,
                'my_studentsid' => $info['friend_studentsid'],
                'friend_uid' => $apply_uid,
                'friend_studentsid' => $info['my_studentsid'],
                'sid' => $sid,
                'add_time' => time(),
                'friend_apply_id' => $apply_id
            ];
            $data[1] = [
                'my_uid' => $apply_uid,
                'my_studentsid' => $info['my_studentsid'],
                'friend_uid' => $uid,
                'friend_studentsid' => $info['friend_studentsid'],
                'sid' => $sid,
                'add_time' => time(),
                'friend_apply_id' => $apply_id
            ];
            db('friend')->insertAll($data);
        }

        return $r == false ? ['status' => 0, 'msg' => '操作失败'] : ['status' => 1, 'msg' => '操作成功'];
    }

}







